package com.hbnu.server.http.handler;

import com.hbnu.tools.FileTool;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

public class WebPageHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        // 确保请求路径为根路径 "/"
        if ("/".equals(request.uri())) {
            // 生成上传表单网页
            String htmlResponse = generateUploadPage();
            // 返回 HTML 网页
            sendHtmlResponse(ctx, HttpResponseStatus.OK, htmlResponse);
        } else if ("/up".equals(request.uri())) {
            request.retain();
            ctx.fireChannelRead(request);
        }else {
            // 如果请求不是根路径，返回 404
            sendHtmlResponse(ctx, HttpResponseStatus.NOT_FOUND, "Page not found");
        }
    }

    // 生成上传页面 HTML
    private String generateUploadPage() {
        return "<!DOCTYPE html>\n" +
                "<html lang=\"zh\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                "    <title>文件上传</title>\n" +
                "    <style>\n" +
                "        body {\n" +
                "            font-family: Arial, sans-serif;\n" +
                "            display: flex;\n" +
                "            justify-content: center;\n" +
                "            align-items: center;\n" +
                "            height: 100vh;\n" +
                "            margin: 0;\n" +
                "            background-color: #f4f4f4;\n" +
                "        }\n" +
                "\n" +
                "        .upload-container {\n" +
                "            text-align: center;\n" +
                "            background-color: #fff;\n" +
                "            padding: 20px;\n" +
                "            border-radius: 8px;\n" +
                "            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);\n" +
                "        }\n" +
                "\n" +
                "        h1 {\n" +
                "            font-size: 24px;\n" +
                "            margin-bottom: 20px;\n" +
                "        }\n" +
                "\n" +
                "        input[type=\"file\"] {\n" +
                "            margin-bottom: 20px;\n" +
                "        }\n" +
                "\n" +
                "        button {\n" +
                "            background-color: #4CAF50;\n" +
                "            color: white;\n" +
                "            padding: 10px 20px;\n" +
                "            border: none;\n" +
                "            border-radius: 5px;\n" +
                "            cursor: pointer;\n" +
                "        }\n" +
                "\n" +
                "        button:hover {\n" +
                "            background-color: #45a049;\n" +
                "        }\n" +
                "\n" +
                "        #fileList {\n" +
                "            margin-top: 20px;\n" +
                "            text-align: left;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <div class=\"upload-container\">\n" +
                "        <h1>选择文件进行上传</h1>\n" +
                "        <input type=\"file\" id=\"fileInput\" multiple />\n" +
                "        <button id=\"uploadBtn\">上传文件</button>\n" +
                "        <div id=\"fileList\"></div>\n" +
                "    </div>\n" +
                "    <script>\n" +
                "        document.getElementById(\"uploadBtn\").addEventListener(\"click\", function() {\n" +
                "            const fileInput = document.getElementById(\"fileInput\");\n" +
                "            const files = fileInput.files;\n" +
                "\n" +
                "            if (files.length === 0) {\n" +
                "                alert(\"请选择文件!\");\n" +
                "                return;\n" +
                "            }\n" +
                "\n" +
                "            const fileListDiv = document.getElementById(\"fileList\");\n" +
                "            fileListDiv.innerHTML = \"<h3>选中的文件:</h3>\";\n" +
                "\n" +
                "            const formData = new FormData();\n" +
                "\n" +
                "            for (let i = 0; i < files.length; i++) {\n" +
                "                formData.append(\"files[]\", files[i]);\n" +
                "\n" +
                "                // 显示文件名\n" +
                "                const fileName = document.createElement(\"p\");\n" +
                "                fileName.textContent = files[i].name;\n" +
                "                fileListDiv.appendChild(fileName);\n" +
                "            }\n" +
                "\n" +
                "            // 模拟上传文件（实际应用中，您可以使用 fetch 或 XMLHttpRequest 发送表单数据）\n" +
                "            fetch(\"http://"+ FileTool.getIP() +":8080/up\", {\n" +
                "                method: \"POST\",\n" +
                "                body: formData,\n" +
                "                mode: 'cors',\n" +
                "            })\n" +
                "            .then(response => response.json())\n" +
                "            .then(data => {\n" +
                "                alert(\"文件上传成功！\");\n" +
                "            })\n" +
                "            .catch(error => {\n" +
                "                alert(\"文件上传失败！\");\n" +
                "                console.error(error);\n" +
                "            });\n" +
                "        });\n" +
                "    </script>\n" +
                "</body>\n" +
                "</html>\n";
    }

    // 返回 HTML 响应
    private void sendHtmlResponse(ChannelHandlerContext ctx, HttpResponseStatus status, String htmlContent) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
        response.content().writeBytes(Unpooled.copiedBuffer(htmlContent, CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        ctx.writeAndFlush(response).addListener(future -> ctx.close());
    }

    // 异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        sendHtmlResponse(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Server error occurred");
    }
}

